package com.raising.modules.sys.service;


import com.google.common.collect.Lists;
import com.raising.framework.service.CrudService;
import com.raising.modules.sys.dao.MsgReceiveDao;
import com.raising.modules.sys.dao.MsgSendDao;
import com.raising.modules.sys.entity.MsgReceive;
import com.raising.modules.sys.entity.MsgSend;
import com.raising.modules.sys.entity.enums.MsgEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
* 消息发送表 Service层
* @author gaoy
* @version 1.0
*/
@Service
@Transactional(readOnly = true)
public class MsgSendService extends CrudService<MsgSendDao, MsgSend> {
    @Autowired
    MsgReceiveDao msgReceiveDao;

    /**
     * 保存消息
     * @author gaoyuan
     * @param msgSend 消息对象内容  【传title与content即可】
     * @param users 消息用户id数组
     */
    @Transactional(readOnly = false)
    public void insertSend(MsgSend msgSend,String[] users){
        StringBuffer sb = new StringBuffer();
        for(int i = 0; i < users.length; i++){
            sb. append(users[i]);
        }
        msgSend.setLevel(0);//级别 -1低 0普通 1高
        msgSend.setUsers(sb.toString());
        msgSend.setStatus("1");//已发送
        msgSend.setType(MsgEnum.notice);
        dao.insert(msgSend);
        List<MsgReceive> msgReceives = Lists.newArrayList();
        for (int i=0;i<users.length;i++){
            if("".equals(users[i].trim())){
                continue;
            }
            MsgReceive msgReceive = new MsgReceive();
            msgReceive.setMsgId(msgSend.getId());
            msgReceive.setUpdateBy(users[i]);
            msgReceive.setUpdateDate(new Date());
            msgReceive.setStatus("0");
            msgReceives.add(msgReceive);
        }
        if(msgReceives.size()>0){
            msgReceiveDao.saveBatch(msgReceives);
        }
    }
}
